﻿using Ewell.BizComponent.UI.Core.VievModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using System.Windows;
using Ewell.BizComponent.UI.Charge.Windows;
using Ewell.BizComponent.UI.Core.Model;
using Autofac;
using Ewell.BizComponent.Service.Model.Dto;
using Ewell.BizComponent.Service.Model.Request;
using Ewell.BizComponent.Service.Server;
using Ewell.BizComponent.Service.IServer;
using Ewell.BizComponent.Service.Model.Response;
using Ewell.Interface.Common.Model.Common;
using MahApps.Metro.Controls.Dialogs;
using Ewell.Interface.Common.Model.GateWay.GateWayUriInfo;
using Ewell.Interface.Common.Model.GateWay.Dto.Dict;
using Ewell.Interface.Common.Utils;
using Ewell.BizComponent.Service.Model.Insur.Response;

namespace Ewell.BizComponent.UI.Charge.ViewModel
{
    /// <summary>
    /// 支付主类
    /// </summary>
    public class CashierVm:ViewModelBase
    {
        public IDialogCoordinator dialogCoordinator { get; set; } = DialogCoordinator.Instance;
        /// <summary>
        /// 支付方式
        /// </summary>
        private List<PayWayVm> _payWayList;
        public List<PayWayVm> payWayList
        {
            get => _payWayList; set
            {
                if (value != _payWayList)
                {
                    _payWayList = value;
                    OnPropertyChanged(nameof(payWayList));
                }
            }
        }
        /// <summary>
        /// 预存账户支付方式
        /// </summary>
        private PayWayVm _prestorePayWay;
        public PayWayVm prestorePayWay
        {
            get => _prestorePayWay;
            set
            {
                if (value != _prestorePayWay)
                {
                    _prestorePayWay = value;
                    OnPropertyChanged(nameof(prestorePayWay));
                }
            }
        }
        /// <summary>
        /// 预存账户之外的支付方式
        /// </summary>
        public List<PayWayVm> _otherPayWayList;
        public List<PayWayVm> otherPayWayList
        {
            get => _otherPayWayList; set
            {
                if (value != _otherPayWayList)
                {
                    _otherPayWayList = value;
                    OnPropertyChanged(nameof(otherPayWayList));
                }
            }
        }
        /// <summary>
        /// 单支付方式下选中的支付方式
        /// </summary>
        private PayWayVm _selectPayWay;
        public PayWayVm selectPayWay
        {
            get => _selectPayWay;
            set
            {
                if (value != _selectPayWay)
                {
                    _selectPayWay = value;
                    OnPropertyChanged(nameof(selectPayWay));
                }
            }
        }
        /// <summary>
        /// 患者信息
        /// </summary>
        private PatientVm _patientVm;
        public PatientVm patientVm
        {
            get => _patientVm; set
            {
                if (value != _patientVm)
                {
                    _patientVm = value;
                    OnPropertyChanged(nameof(patientVm));
                }
            }
        }
        /// <summary>
        /// 已选择的医保费别
        /// </summary>
        private PatientTypeVm _selectedPatientType;
        public PatientTypeVm selectedPatientType
        {
            get
            {
                return _selectedPatientType;
            }
            set
            {
                if (_selectedPatientType != value)
                {
                    _selectedPatientType = value;
                    OnPropertyChanged(nameof(selectedPatientType));
                }
            }
        }
        /// <summary>
        /// 收费信息
        /// </summary>
        private ChargingInfoVm _chargingInfo;
        public ChargingInfoVm chargingInfo
        {
            get => _chargingInfo; set
            {
                if (_chargingInfo != value)
                {
                    _chargingInfo = value;
                    OnPropertyChanged(nameof(chargingInfo));
                }
            }
        }

        /// <summary>
        /// 医保预算结果
        /// </summary>
        public OutPayResponse preOutPayResponse { get; set; }

        public IOutSettlementServer outSettlementServer { get; set; }=Global.Container.Resolve<IOutSettlementServer>();
        public IPaymentServer paymentServer { get; set; }=Global.Container.Resolve<IPaymentServer>();

        public Window localWindow { get; set; }

        public ICommand Init => new RelayCommand(async (object param) =>
        {
            try
            {
                #region 支付方式
                List<PayWayVm> payWayList = new List<PayWayVm>();
                DictPayWayDubboService dictPayWayDubboService = new DictPayWayDubboService();
                PayWayQueryRequest payWayQueryRequest = new PayWayQueryRequest()
                {
                    enabledFlag = "1",
                    athenaMenuId = LoginInfo.menuId,
                    patientTypeNo = selectedPatientType?.no,
                };
                var gateWayPayWay = dictPayWayDubboService.queryPayWayListByExample.Post<List<PayWayResponse>>(payWayQueryRequest).CheckState("诊间挂号");
                if (gateWayPayWay.@object == null || gateWayPayWay.@object?.Count <= 0) throw new SpeedException("诊间挂号", "未查询到支付方式!请检查系统设置!");
                foreach (var item in gateWayPayWay.@object)
                {
                    PayWayVm payWay = item.CopyProperties<PayWayVm>();
                    payWay.isDefault = "1".Equals(item.defaultFlag);
                    if (payWay.interfaceId.HasValue)
                    {
                        if (!string.IsNullOrWhiteSpace(this.patientVm.patientId))
                        {
                            //查询账户余额
                            var queryBalanceResp = paymentServer.QueryBalance(payWay.interfaceId.Value, new QueryBalanceReq() { accountOwnerNo = this.patientVm.patientId });
                            payWay.balance = queryBalanceResp.accountBalance;
                        }
                        //获取支付金额
                        if (item.autoGetPayAmtFlag == "1")
                        {
                            QueryPayAmountResponse amountResponse = paymentServer.QueryPaymentAmount(payWay.interfaceId.Value, new QueryPayAmountRequest()
                            {
                                hisBizNo = chargingInfo.settlementId.ToString(),
                                hisBizTypeCode = chargingInfo.settlementTypeCode,
                                insurPayAmt = preOutPayResponse?.insurReimAmount,
                                patientId = this.patientVm.patientId,
                                payWayNo = item.no,
                                payMtInsurInfoId = string.IsNullOrWhiteSpace(preOutPayResponse.payMtInsurInfoId) ? null : long.Parse(preOutPayResponse.payMtInsurInfoId),
                            });
                            if (amountResponse.payAmt > chargingInfo.recAmount)
                            {
                                throw new SpeedException("HISBIZ", $"获取的支付金额不能大于应付金额,接口【{item.interfaceName}】");
                            }
                            payWay.amount = amountResponse.payAmt;
                        }
                    }
                    payWay.balance = payWay.balance ?? 0;
                    payWayList.Add(payWay);
                }
                this.payWayList = payWayList;
                #endregion

                this.prestorePayWay = this.payWayList.FirstOrDefault(f => f.no == "HIS001");
                this.otherPayWayList = this.payWayList.Where(f => f.no != "HIS001").ToList();
                payWayList?.ForEach(e =>
                {
                    e.payAmt = 0;
                    e.paySuccess = null;
                    e.payErrorMsg = string.Empty;
                });
                //存在账户默认账户支付
                if (prestorePayWay != null)
                {
                    //余额充足全部支付
                    if (prestorePayWay.balance >= chargingInfo.recAmount - otherPayWayList.Sum(s => s.amount))
                    {
                        prestorePayWay.amount = chargingInfo.recAmount.Value - otherPayWayList.Sum(s => s.amount);
                    }
                    else//余额不足剩余的填到默认或者第一个支付方式
                    {
                        prestorePayWay.amount = prestorePayWay.balance ?? 0;
                        //通过接口没有获取到支付金额再进行默认
                        if (otherPayWayList.Sum(s => s.amount) == 0)
                        {
                            PayWayVm payWay = otherPayWayList?.FirstOrDefault(f => f.isDefault);
                            if (payWay != null) payWay.amount = chargingInfo.recAmount.Value - prestorePayWay.amount;
                            else
                            {
                                payWay = otherPayWayList?.FirstOrDefault();
                                payWay.amount = chargingInfo.recAmount.Value - prestorePayWay.amount;
                            }
                        }
                    }
                }
                else//不存在账户按照设置的默认支付
                {
                    PayWayVm payWay = otherPayWayList?.FirstOrDefault(f => f.isDefault);
                    if (payWay == null) payWay = otherPayWayList?.FirstOrDefault();
                    if (payWay != null) payWay.amount = chargingInfo.recAmount.Value;
                }
                #region 单支付方式下拉框默认选中设置的 没有设置的默认第一个
                foreach (PayWayVm item in this.otherPayWayList)
                {
                    if (item.isDefault)
                        this.selectPayWay = item;
                }
                if (this.selectPayWay == null)
                    this.selectPayWay = this.otherPayWayList.FirstOrDefault();
                #endregion
            }
            catch (Exception ex)
            {
                LogHelper.Debug($"初始化支付方式异常!{ex}");
                await this.dialogCoordinator.ShowMessageAsync(this, "警告", $"初始化结算方式异常!{ex.Message}");
                return;
            }
        });

        public ICommand paySetl => new RelayCommand(async (object param) =>
        {
            //校验
            if (payWayList.Where(w => w.amount > 0).Sum(w => w.amount) != this.chargingInfo.recAmount)
            {
                await this.dialogCoordinator.ShowMessageAsync(this, "警告" , $"支付金额不等于应收金额!");
                return;
            }
            var onlinePayList = payWayList.Where(x => x.interfaceId.HasValue && x.amount > 0 && x.paySuccess != true)?.ToList();
            if (onlinePayList.Count > 0)
            {
                onlinePayList.ForEach(x => x.payQrCode = string.Empty);
                OnlinePayVm onlinePayVm = new OnlinePayVm();
                onlinePayVm.patientVm = this.patientVm;
                onlinePayVm.chargingInfo = this.chargingInfo;
                onlinePayVm.payWayList = onlinePayList;
                OnlinePayWindow onlinePayFrm = new OnlinePayWindow(onlinePayVm);
                onlinePayFrm.Owner = this.localWindow;
                onlinePayVm.localWindows = onlinePayFrm;
                onlinePayFrm.PayAll();
            }

            if (payWayList.Any(a => a.interfaceId.HasValue && a.amount > 0 && a.paySuccess != true))
            {
                var payWayFail = payWayList.FirstOrDefault(f => f.interfaceId.HasValue && f.amount > 0 && f.paySuccess != true);
                await this.dialogCoordinator.ShowMessageAsync(this, "警告", $"支付方式【{payWayFail.name}】支付金额【{payWayFail.amount}】失败！请重试!");
                return;
            }
        });

        /// <summary>
        /// 取消支付
        /// </summary>
        public ICommand paySetlCancel => new RelayCommand(async (object param) =>
        {
            var onlinePayList = payWayList.Where(x => x.interfaceId.HasValue && x.paySuccess == true)?.ToList();
            if (onlinePayList.Count > 0)
            {
                OnlinePayVm onlinePayVm = new OnlinePayVm();
                onlinePayVm.patientVm = this.patientVm;
                onlinePayVm.chargingInfo = this.chargingInfo;
                onlinePayVm.payWayList = onlinePayList;
                OnlinePayWindow onlinePayFrm = new OnlinePayWindow(onlinePayVm);
                onlinePayFrm.Owner = this.localWindow;
                onlinePayVm.localWindows = onlinePayFrm;
                onlinePayFrm.RefundAll();
            }

            if (payWayList.Any(a => a.interfaceId.HasValue && a.paySuccess == true))
            {
                await this.dialogCoordinator.ShowMessageAsync(this, "警告", $"还有未退费的支付金额！");
                return;
            }
        });
        /// <summary>
        /// 支付失败重试
        /// </summary>
        public ICommand rePay => new RelayCommand((object payWay) =>
        {
            PayWayVm payWayVm = payWay as PayWayVm;
            var rePayWayList = this.payWayList.Where(w => w.no == payWayVm.no).ToList();
            rePayWayList.ForEach(x => x.payQrCode = string.Empty);
            OnlinePayVm onlinePayVm=new OnlinePayVm();
            onlinePayVm.patientVm = this.patientVm;
            onlinePayVm.chargingInfo = this.chargingInfo;
            onlinePayVm.payWayList = rePayWayList;
            OnlinePayWindow onlinePayFrm = new OnlinePayWindow(onlinePayVm);
            onlinePayFrm.Owner = this.localWindow;
            onlinePayVm.localWindows = onlinePayFrm;
            onlinePayFrm.PayAll();
        });
        
    }
}
